<route lang="json5">
	{
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '参数配置',
	enablePullDownRefresh: false,
	"app-plus": {
	"bounce": "none"
	}
	},
	}
</route>
<template>
	<view style="display: flex; flex-direction: column; height: 100vh;">
		<view style="position: sticky; top: 0; z-index: 9999">
			<wd-navbar title="参数配置" :bordered="false">
				<template #left>
					<wd-icon name="thin-arrow-left" size="16px" color="white" @click="goBack"></wd-icon>
				</template>
				<template #right>
					<text @click="cancelManageHandle" style="color:#fff">{{manageMode?'取消管理':'管理'}}</text>
				</template>
			</wd-navbar>
		</view>
		<scroll-view scroll-y="true" :scroll-top="scrollTop" :scroll-into-view="scrollIntoView"
			style="flex: 1;background-color:  #f4f4f4;">
			<template v-for="(item,index) in form.ruleList" :key="index">
				<view class="card" :id="`item-${index}`" :class="[item.max == 0?'warning':'']">
					<view class="check" v-if="manageMode" @click="delHandle(index)">
						<text class="iconfont icon-jianqu"></text>
					</view>
					<view class="content">
						<view class="range">
							<view class="title">
								<text class="index">{{index + 1}}</text>
							</view>
							<view class="label">
								区间
							</view>
							<view class="row" v-if="manageMode">
								<thInput type="number" v-model:value="item.min" suffix="万" placeholder="最小值" border>
								</thInput>
								<text class="split">-</text>
								<thInput type="number" v-model:value="item.max" suffix="万" placeholder="最大值"
									@change="onChange(item,index)" border></thInput>
							</view>
							<view v-else>
								<text class="num">
									<text>{{item.min}}</text> {{item.min===0?'':'万'}}
								</text>
								<text class="split">-</text>
								<text class="num">
									<text>{{item.max}}</text> 万
								</text>
							</view>
							<view class="label">音频</view>
							<view>
								<th-button v-if="item.voiceUrl" size="small"
									:type="item.id === inPlay?'success':'primary'"
									style="margin-right:15rpx;width:45rpx" @click="playVoice(item)">
									<text v-if="item.id === inPlay" class="iconfont icon-zanting"></text>
									<text v-else class="iconfont icon-bofang"></text>
								</th-button>
								<th-button v-if="manageMode" type="primary" size="small"
									@click="openFileHandle(item)">{{item.voiceUrl?'更换音频':'上传音频'}}</th-button>
							</view>
						</view>
					</view>
				</view>
				<view v-if="manageMode" class="tool">
					<text @click="addItem(index)">+</text>
				</view>
			</template>

			<view v-if="manageMode" style="position:sticky;bottom:0;padding:15rpx;background:#fff;">
				<th-button type="primary" size="flex" @click="directSave">保存配置</th-button>
			</view>
		</scroll-view>

	</view>

</template>

<script lang="ts" setup>
	import { openFile } from './func'
	import thInput from '@/pages/pm/assay-report/component/th-input.vue';
	import thButton from '@/pages/pm/assay-report/component/th-button.vue';
	import { voiceList, updateConfig } from '@/service/brain';
	import cache from '@/utils/cache';
	import showModal from '@/utils/modal';

	const innerAudioContext = uni.createInnerAudioContext();

	const inPlay = ref('');
	const scrollTop = ref(0);
	const scrollIndex = ref(0);
	const scrollIntoView = computed(() => {
		return 'item-' + scrollIndex.value
	})

	const goBack = () => {
		uni.navigateBack();
	};

	const form = ref({
		"id": 0,
		"ruleList": []
	})

	const manageMode = ref(false)

	const addItem = (index) => {
		form.value.ruleList.splice(index + 1, 0, {
			"id": 0,
			"min": form.value.ruleList[index].max,
			"max": 0,
			"value": 0,
			"type": 0,
			"voiceUrl": "",
		})
		scrollIndex.value = index + 1;
	}

	const playVoice = (item) => {
		if (inPlay.value === item.id) {
			innerAudioContext.stop();
			inPlay.value = '';
			return;
		};
		innerAudioContext.stop();
		innerAudioContext.src = item.voiceUrl;
		if (plus.device.getVolume() < 0.1) {
			uni.showToast({
				title: '播放音量可能过低',
				icon: 'none'
			})
		}
		innerAudioContext.play();

		inPlay.value = item.id;

		innerAudioContext.onEnded(() => {
			//自动切换事件
			inPlay.value = '';
		});
	}


	const delHandle = (index) => {
		form.value.ruleList.splice(index, 1)
	}

	const onChange = (item, index) => {
		if (form.value.ruleList[index + 1]) {
			form.value.ruleList[index + 1].min = item.max
		}
	}

	const cancelManageHandle = () => {
		manageMode.value = !manageMode.value;
		getFormData()
	}

	const saveHandle = (resolve ?: any) => {
		uni.showLoading({
			title: '正在保存',
			mask: true
		})
		const formData = JSON.parse(JSON.stringify(form.value));

		formData.ruleList = formData.ruleList.map(item => {
			item.min = item.min * 10000
			item.max = item.max * 10000
			return item
		})
		updateConfig(formData).then(res => {
			if (res.code === 0) {
				uni.hideLoading();
				uni.showToast({
					title: '保存成功',
					mask: true
				})
				manageMode.value = false;
				uni.$emit('refresh')
				if (resolve) {
					resolve(true)
				} else {
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1000)
				}

			} else {
				resolve(false)
			}
		})
	}

	const directSave = () => {
		saveHandle();
	}

	const indirectForm = () => {
		return new Promise((resolve) => {
			saveHandle(resolve)
		})
	}

	const openFileHandle = (item) => {
		openFile((filePath) => {

			if (filePath) {
				uni.showLoading({
					title: '正在上传',
					mask: true
				})
			} else {
				uni.showToast({
					title: '请尝试打开文件管理中选择音频文件',
					mask: true,
					icon:'none',
					duration:3000
				})
			}
			uni.uploadFile({
				url: `${import.meta.env.VITE_SERVER_BASEURL}/oss/sysOss/upload`,
				filePath,
				name: 'file',
				header: {
					'Authorization': cache.get('token')
				},
				success: (res) => {
					const resp = JSON.parse(res.data)

					if (resp.code === 0) {
						item.voiceUrl = resp.data.url;
						uni.showToast({
							title: '上传完成'
						})
						return;
					}
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				},
				fail(e) {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				},
				complete() {
					uni.hideLoading();
				}
			})
		})
	}

	const getFormData = () => {
		voiceList().then(res => {
			if (res.code === 0) {
				const ruleList = res.data.ruleList.map(item => {
					item.min = item.min / 10000
					item.max = item.max / 10000
					return item
				})
				form.value = res.data;
				form.value.ruleList = ruleList;
			}
		})
	}

	onMounted(() => {
		getFormData()
	})

	onBackPress(() => {
		innerAudioContext.destroy();
		if (!manageMode.value) return false;
		showModal({
			title: '提示',
			content: '退出前是否保存？',
			showCancel: true,
			cancelText: '保存',
			confirmText: '直接退出',
			confirm: async () => {
				const isSave = await indirectForm();
				if (isSave) {
					manageMode.value = false;
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1000)

				}
			},
			cancel() {
				manageMode.value = false;
				uni.navigateBack({
					delta: 1
				})
			}
		});
		return true;
	})
</script>

<style lang="scss" scoped>
	@import url('@/static/iconfont/iconfont.css');

	.card {
		margin: 20rpx;
		display: flex;
		align-items: center;
		background:#fff;
		// box-shadow: 0 0 10rpx 0 #bfbfbf;
		border-radius: 10rpx;

		.check {
			margin: 0 15rpx 0 20rpx;
			color: #f56c6c;
 
			.icon-jianqu {
				font-size: 38rpx;
			}
		}

		.content {
			flex: 1;
		}

		&.warning {
			box-shadow: 0 0 10rpx 0 #f56c6c;
		}
	}

	.range {
		padding: 15rpx;
		border-bottom: 1rpx solid #f1f1f1;
		border-radius: 15rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		display: flex;
		border-bottom: 1rpx solid #bfbfbf;
		padding-bottom: 15rpx;
		align-items: center;

		.index {
			font-size: 36rpx;
			font-weight: bold;
		}
	}



	.label {
		padding: 15rpx 0;
		font-size: 28rpx;
		color: #999;
	}

	.split {
		color: #bfbfbf;
		margin: 0 10rpx;
	}

	.num {
		color: #999;
		font-size: 24rpx;

		text {
			font-size: 40rpx;
			color: #000;
		}
	}

	.tool {
		border-radius: 10rpx;
		margin-top: 15rpx;
		text-align: center;
		font-size: 38rpx;
		color: #bfbfbf;
	}

	:deep(.wd-navbar__right--hover) {
		background: none;
	}
</style>